//
//  WebViewController.swift
//  kz
//
//  Created by Tech_001 on 10/8/2017.
//  Copyright © 2017 Tech_001. All rights reserved.
//customScheme

import Foundation
import UIKit
import JavaScriptCore
import Eagleeyes.DevicePrint
import SwiftyJSON
class WebViewController: UIViewController, UIWebViewDelegate{
  
    let customScheme = "customredirect"
    let customHttpsScheme = "customredirects"
    
    var webView: UIWebView?
    var signLoging:Bool?
    var url: String?
 //   var url2: String?="http://192.168.3.4/index.php";
    var bottomOffset: CGFloat = 0
    var isLoadjsCode = false
    var _loadView: UIView?
    var loadViewOffsetY: CGFloat = 0
    var hideNavigationBar = false
    var jsContext: JSContext!
    var isKefu = false
    var isShowRefresh:Bool = true
    var isBackHome :Bool = false
    var isBack : Bool = false
    var needSetUserInfo = false
    var isEagleeyes :Bool = false
    var isFist:Bool = true
    var isHelper = false
    var navigationBarExist = true// 存在导航栏
    // 如果需要拦截系统返回按钮就重写该方法返回 false
    override func currentViewControllerShouldPop() -> Bool {
          ToolHelper.statisticsPage(pageName:"h5页面-顶部功能-返回")
        if(self.webView?.canGoBack)!{
            self.webView?.goBack()
        }else{
            if isBack == false {
                let dialogMessage = UIAlertController(title: "提示", message: "确认离开当前页面?", preferredStyle: .alert)
                dialogMessage.view.tintColor = UIColor.black
                
                let ok = UIAlertAction(title: "确定", style: .default, handler: { (action) -> Void in
                    print("确定")
                    if self.isBackHome == true{
                        ToolHelper.statisticsPage(pageName:"顶部功能-返回-确定")
                        self.navigationController?.popToRootViewController(animated: true)
                    }else{
                         ToolHelper.statisticsPage(pageName:"顶部功能-返回-取消")
                        self.navigationController?.popViewController(animated: true)
                    }
                })
                let cancelExit = UIAlertAction(title: "取消", style: .default, handler: { (action) -> Void in
                })
                dialogMessage.addAction(ok)
                dialogMessage.addAction(cancelExit)
                
                self.tabBarController?.present(dialogMessage, animated: true, completion: nil)
            }
        }
        return isBack
    }
    
    override func viewDidLoad() {
        reqestLoging()
        self.webView = UIWebView()
        
        let item = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
        self.navigationItem.backBarButtonItem = item;
        
        self.navigationItem.titleView = UIImageView.init(image: UIImage.init(named: "navi_icon_titleLogo"))
        self.navigationController?.navigationBar.shadowImage = UIImage()
        // 设置导航栏默认返回按钮
        self.leftButtonActionWithImg("icon_default_back")
 
        let frame = self.view.frame
        
        let frameY:CGFloat = self.navigationBarExist ? kNavigationBarHeight : 0 ;
        
        webView!.frame = CGRect(x: 0, y: frameY, width: frame.width, height: frame.height - frameY)
        webView?.scalesPageToFit = true
        
        if  isShowRefresh {
            
            let rightButton = UIButton(type: .custom)
            rightButton.setTitleColor(UIColor.init("333333"), for: .normal)
            rightButton.setTitleColor(UIColor.gray, for: .selected)
            rightButton.setTitleColor(UIColor.gray, for: .highlighted)
            rightButton.setTitle("刷新", for: .normal)
            rightButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            rightButton.frame = CGRect.init(x: 0, y: 0, width: 30, height: 20)
            rightButton.addTarget(self, action: #selector(self.webViewReload), for: .touchUpInside)
            
            let fullScreenButton = UIButton(type: .custom)
            fullScreenButton.setTitleColor(UIColor.init("333333"), for: .normal)
            fullScreenButton.setTitleColor(UIColor.gray, for: .selected)
            fullScreenButton.setTitleColor(UIColor.gray, for: .highlighted)
            fullScreenButton.setTitle("关闭", for: .normal)
            fullScreenButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            fullScreenButton.frame = CGRect.init(x: 0, y: 0, width: 30, height: 20)
            fullScreenButton.addTarget(self, action: #selector(self.actionClosePage), for: .touchUpInside)
           
            let rightItem = UIBarButtonItem.init(customView: rightButton)
            let fullScreenItem = UIBarButtonItem.init(customView: fullScreenButton)
            
            self.navigationItem.rightBarButtonItems = [rightItem, fullScreenItem]
        }else{
            
            let fullScreenButton = UIButton(type: .custom)
            fullScreenButton.setTitleColor(UIColor.init("333333"), for: .normal)
            fullScreenButton.setTitleColor(UIColor.gray, for: .selected)
            fullScreenButton.setTitleColor(UIColor.gray, for: .highlighted)
            fullScreenButton.setTitle("关闭", for: .normal)
            fullScreenButton.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            fullScreenButton.frame = CGRect.init(x: 0, y: 0, width: 30, height: 20)
            fullScreenButton.addTarget(self, action: #selector(self.actionClosePage), for: .touchUpInside)
            let fullScreenItem = UIBarButtonItem.init(customView: fullScreenButton)
            
            self.navigationItem.rightBarButtonItem = fullScreenItem
        }
      
        self.view.addSubview(webView!)

        /**** Interface ****/
        if self.url?.contains("activity=yeiQC5hLS2tD5jq6flMl3dvympPZ7K9r") ?? false {
            self.needSetUserInfo = true
        }
//        self.url = "https://game.manbetlegend.com/1.html"
        if let urlString = self.url {
             print("WebView=====URL====>\(urlString)")
            if let urlObj = URL(string: urlString){
                var request = URLRequest(url: urlObj)
                webView!.delegate = self
                webView!.loadRequest(request)
            }
        }
        self.jsContext = self.webView!.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext
                let model = SwiftJavaScriptModel()
               self.jsContext.setObject(model, forKeyedSubscript: "ios" as NSCopying & NSObjectProtocol)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
   //     self.navigationController?.navigationBar.topItem?.title = "";
        self.navigationController?.setNavigationBarHidden(self.hideNavigationBar, animated: true)
        if self.hideNavigationBar {
            self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        }
        
        if isShowRefresh == false {
            if let urlString = self.url {
                print("WebView=====URL====>\(urlString)")
                if let urlObj = URL(string: urlString){
                    var request = URLRequest(url: urlObj)
                    webView!.delegate = self
                    webView!.loadRequest(request)
                }
            }
        }
      
    }
    

    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        if (self.isEagleeyes == true){
            if (request.url?.scheme != "e2"){
                return true
            }
            if (request.url?.fragment == nil){
                return true
            }
            let blackBox : String =  DevicePrint.getBlackBox() ?? ""
            webView.stringByEvaluatingJavaScript(from: "document.getElementById('\(request.url?.fragment ?? "" )').value = '\(blackBox)'")
            return false
        }else{
            if let app = WebViewApp.getInstance(request.url!) {
                WebViewApp.route(app)
                return false
            }

            if request.url?.scheme == self.customScheme {
                let newUrl = URL(string: request.url!.absoluteString.replacingOccurrences(of: self.customScheme, with: "http"))
                UIApplication.shared.openURL(newUrl!)
                return false
            }else if request.url?.scheme == self.customHttpsScheme {
                let newUrl = URL(string: request.url!.absoluteString.replacingOccurrences(of: self.customHttpsScheme, with: "https"))
                UIApplication.shared.openURL(newUrl!)
                return false
            }


            print(navigationType)
            //網銀
            /*if request.url!.host == "api.089458.com" && request.url!.path == "/API/Bank.aspx" {
             UIApplication.shared.openURL(request.url!)
             return false
             }*/
             return true
        }
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
      //  if isHelper == false{
            if self._loadView != nil {
                self._loadView?.removeFromSuperview()
            }
            self._loadView = UIHelper.initLoadView(self, withMessage: nil, offsetY: loadViewOffsetY)
            self.view.addSubview(self._loadView!)
    //    }
      
        for cookie in HTTPCookieStorage.shared.cookies(for: URL(string: url!)!)! {
            print("Cookie: \(cookie.name), value: \(cookie.value)")
        }
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
       print("WebView Target: \(webView.request?.url?.absoluteString)")
        self.jsContext = self.webView!.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext
         let model = SwiftJavaScriptModel()
        self.jsContext.setObject(model, forKeyedSubscript: "ios" as NSCopying & NSObjectProtocol)
        
        if (self.isEagleeyes == true){//鷹眼
            let blackBox : String =  DevicePrint.getBlackBox() ?? ""
            webView.stringByEvaluatingJavaScript(from: "document.getElementById('bbox').value = '\(blackBox)'")
            webView.stringByEvaluatingJavaScript(from: "var DevicePrint = { injectInto: function(id) { var iframe = document.createElement('IFRAME');  iframe.setAttribute('src', 'e2://blackbox/fill#' + id);  document.documentElement.appendChild(iframe);  iframe.parentNode.removeChild(iframe); iframe = null; } }")
        }

        webView.stringByEvaluatingJavaScript(from: "window.open = function (open) { return function  (url, name, features) { var newurl = url.replace('https://','\(self.customHttpsScheme)://'); newurl = newurl.replace('http://','\(self.customScheme)://'); window.location.href = newurl; return window; }; } (window.open);")
        //mt 20171229


        let defaults = UserDefaults.standard

         var mtusername = ""
        if UserHelper.getLoginStatus() {
            mtusername = defaults.value(forKey: DefaultKey.USER_LOGIN_NAME) as? String ?? ""
        }
        
        if self.url?.contains("addcs=a22e83d19bf3d90f")  == true {
            
        }else{
           webView.stringByEvaluatingJavaScript(from:"javascript: var masigle = true; var setIntVal=setInterval(function(){var msnElements = document.getElementsByName('msn'); if(msnElements.length>=1){clearInterval(setIntVal); if(msnElements&&masigle){for(var i=0;i<msnElements.length;i++){msnElements[i].value='\(mtusername)'} masigle = false;}} var funcHistory = document.getElementById('history');funcHistory.style.overflow='visible';var funcQueue = document.getElementById('queue'); funcQueue.style.display='block';var funcDiv=document.getElementById('funcDiv');funcDiv.style.position='fixed';funcHistory.style.bottom='0px';funcHistory.style.top='0px';funcQueue.style.zIndex=0; } ,500);")
        }

      
//        webView.stringByEvaluatingJavaScript(from:"document.body.style.zoom=1.0;");
        
//        webView.stringByEvaluatingJavaScript(from:"document.documentElement.style.webkitUserSelect='none';");
//       webView.stringByEvaluatingJavaScript(from:"document.documentElement.style.webkitTouchCallout='none';");
        /*js调用swift方法开始*/
        // if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        //window.webkit.messageHandlers.method.postMessage(param);
        if isLoadjsCode {
            print("传递的参数:\(UserDefaults.standard.string(forKey: DefaultKey.USER_LOGIN_NAME)! as NSString)   \(UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! as NSString)")
            self.jsContext.evaluateScript("getAccount('\( UserDefaults.standard.string(forKey: DefaultKey.USER_LOGIN_NAME)! as NSString)' ,'\( UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! as NSString)')")
        }
        if needSetUserInfo{
            print("传递的参数:\(UserDefaults.standard.string(forKey: DefaultKey.USER_LOGIN_NAME)! as NSString)   \(UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! as NSString)")
            self.jsContext.evaluateScript("setActivityParam('\( UserDefaults.standard.string(forKey: DefaultKey.USER_LOGIN_NAME)! as NSString)' ,'\( UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! as NSString)')")
        }
//        self.jsContext = self.webView!.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext
//         let model = SwiftJavaScriptModel()
//        self.jsContext.setObject(model, forKeyedSubscript: "ios" as NSCopying & NSObjectProtocol)
        /*js调用swift方法结束*/
        self._loadView?.removeFromSuperview()
//        if isHelper {
//            if self.isFist{
//                self.isFist = false
//                self.webView?.reload()
//                self.startTimer()
//            }
//        }

    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        if self._loadView != nil {
            self._loadView?.removeFromSuperview()
        }
    }
    
    func webViewDismiss(){
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc func webViewReload(){
        ToolHelper.statisticsPage(pageName:"h5页面-顶部功能-刷新")
        self.webView?.reload()
       // self.startTimer()
//        self.webView?.removeFromSuperview()
//        viewDidLoad()
    }
    //mt
    func reqestLoging(){
        if(self.signLoging != nil){
        if(self.signLoging)!{
        RequestHelper.get(atPath:"/clientsAPIs/GetProfileInfo",withCompletion:{data in

            self.signLoging = nil;
             let json = JSON(data)
             print("基本信息:\(json)")
            if json["m"].string == "9999"{
                DispatchQueue.main.async {
                    if self.isKefu == false{
                        LoginViewController.loginIfNeedController(currentController: self) {}
                    }
                }
            }
        }, withError: { error in
            print(error)
            DispatchQueue.main.async {
              
                UIHelper.alertSimpleMessage(about: "网络链接不稳定，请稍后重试。\(getErrorString())", withDescription: "", in: self)
                self._loadView?.removeFromSuperview()
            }
        })
        }
        }
    }
    
    @objc func actionClosePage(){
        let dialogMessage = UIAlertController(title: "提示", message: "确认离开当前页面?", preferredStyle: .alert)
        dialogMessage.view.tintColor = UIColor.black
         ToolHelper.statisticsPage(pageName:"h5页面-顶部功能-关闭")
        let ok = UIAlertAction(title: "确定", style: .default, handler: { (action) -> Void in
            if self.isBackHome == true{
                  ToolHelper.statisticsPage(pageName:"顶部功能-关闭-确定")
                self.navigationController?.popToRootViewController(animated: true)
            }else{
                  ToolHelper.statisticsPage(pageName:"顶部功能-关闭-取消")
                self.navigationController?.popViewController(animated: true)
            }
        })
        let cancelExit = UIAlertAction(title: "取消", style: .default, handler: { (action) -> Void in
        })
        dialogMessage.addAction(ok)
        dialogMessage.addAction(cancelExit)
        self.tabBarController?.present(dialogMessage, animated: true, completion: nil)
    }
    
    deinit {
      //  if isHelper {
     //       JWCacheURLProtocol.cancelListeningNetWorking()
    //    }
        
    }
    
    func startTimer() {
        let time: TimeInterval = 5.0
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
            //code
            self.updataSecond()
            print("秒后输出")
        }
    }
    
    func updataSecond() {
        self.webView?.reload()
    }
    
    // 导航栏左边按钮
    func leftButtonActionWithImg(_ image: String) {
        let naviLeftButton = UIButton.init(type: UIButton.ButtonType.custom)
        naviLeftButton.frame = CGRect.init(x: 0, y: 0, width: 22, height: 22);
        naviLeftButton.setBackgroundImage(UIImage.init(named: image), for: UIControl.State.normal)
        naviLeftButton.setBackgroundImage(UIImage.init(named: image), for: UIControl.State.highlighted)
        naviLeftButton.addTarget(self, action: #selector(doLeftNaviAction), for: UIControl.Event.touchUpInside)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: naviLeftButton)
    }
    
    // 导航栏左边按钮点击
    @objc func doLeftNaviAction() {
        self.actionClosePage()
    }
}
